package cn.zb.config;


import cn.zb.entity.auth.SysUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @Description:Security 从请求头中获取token验证身份
 * @Author:
 * @Date: 2024/11/22 18:44
 */
@Component
public class TokenSecurityConfig implements ServerSecurityContextRepository {
    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
        return Mono.empty();
    }

    @Override
    public Mono<SecurityContext> load(ServerWebExchange exchange) {
        // 每次请求从请求头获取是否有token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        // 从redis查询数据
        SysUser user = (SysUser) redisTemplate.opsForValue().get("login:"+token);
        // 如果存在数据 就存储在上下文中 用于后续过滤器鉴权
        if(user != null){
            UsernamePasswordAuthenticationToken upat=
                    new UsernamePasswordAuthenticationToken(user.getUsername(),null,user.getAuthorities());
            SecurityContextImpl sci = new SecurityContextImpl(upat);
            return Mono.justOrEmpty(sci);
        }
        return Mono.empty();
    }
}
